package cn.baddonkey.superquery.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BeanUtils {

    public static <T> T transform(Object source, Class<T> cls) {
        try {
            T t = cls.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            log.error("BeanUtils transform error,", e);
            throw new RuntimeException(e);
        }
    }

    public static <T, M> List<T> batchTransform(List<M> source, Class<T> cls) {
        if (source == null || source.size() == 0) {
            return new ArrayList<>();
        }
        List<T> list = new ArrayList<>();
        for (M o : source) {
            T transform = BeanUtils.transform(o, cls);
            list.add(transform);
        }
        return list;
    }

    public static <T, M> Page<T> copyPage(Page<M> source, Class<T> cls) {
        if (source == null) {
            return new Page<>();
        }
        List<M> records = source.getRecords();
        List<T> list = BeanUtils.batchTransform(records, cls);
        Page<T> page = new Page<>();
        page.setRecords(list);
        page.setCurrent(source.getCurrent());
        page.setPages(source.getPages());
        page.setSize(source.getSize());
        page.setTotal(source.getTotal());
        return page;
    }
}
